package com.tianxiabuyi.utils;

import com.dbay.apns4j.IApnsService;
import com.dbay.apns4j.impl.ApnsServiceImpl;
import com.dbay.apns4j.model.ApnsConfig;
import com.dbay.apns4j.model.Payload;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * iOS推送工具类
 * @author yh
 * 2015-05-24
 */
public final class PushUtil {
    /**
     * 医院id和对应的IApnsService
     */
    private static HashMap<String, IApnsService> apnsServices = new HashMap<String, IApnsService>();

    private PushUtil() {
        throw new Error("Don't let anyone instantiate this class");
    }

    /**
     * 发送上架产品推送
     *
     * @param hospitalId
     * @return
     */
    public static void push(HashMap<String, Object> param) {
        push(param, false);
    }

    /**
     * 发送沙盒产品推送
     *
     * @param hospitalId
     * @return
     */
    public static void pushDev(HashMap<String, Object> param) {
        push(param, true);
    }

    /**
     * 发送推送
     *
     * @param hospitalId
     * @param isDev
     *            true为测试产品
     * @return
     */
    @SuppressWarnings("unchecked")
    private static void push(HashMap<String, Object> param, boolean isDev) {
        String hospitalId = param.get("hospital") + "";
        String type = Tools.getDesc(param.get("app_type"), "");
        String fileName = hospitalId + type + "pro.p12";
        if (isDev) {
            fileName = hospitalId + type  + "dev.p12";
        }
        // 取IApnsService
        IApnsService apnsService = apnsServices.get(fileName);
        if (null == apnsService) {
            System.out.println("创建" + fileName + "推送IApnsService");

            ApnsConfig config = new ApnsConfig();
            InputStream is = PushUtil.class.getResourceAsStream("/push/"
                    + fileName);
            config.setKeyStore(is);
            config.setDevEnv(isDev);
            config.setPassword("eeesysyh");
            config.setPoolSize(10);
            config.setName(fileName);
            apnsService = ApnsServiceImpl.createInstance(config);

            // 添加到apnsServices
            apnsServices.put(fileName, apnsService);
        }

        // 发送通知
        List<String> tokens = (List<String>) param.get("tokens");
        for (int i = 0; i < tokens.size(); i++) {
            String token = tokens.get(i); // 设备号
            String alert = Tools.getDesc(param.get("alert") + "", "");
            Payload payload = new Payload();
            payload.setAlert(alert);
            payload.setBadge(0);

            for (Map.Entry<String, Object> entry : param.entrySet()) {
                String key = entry.getKey();
                if ((!"tokens".equals(key)) && (!"alert".equals(key))
                        && (!"hospital".equals(key))) {
                    payload.addParam(entry.getKey(), entry.getValue());
                }
            }
            apnsService.sendNotification(token, payload);
        }
    }
}